package com.hb.anative

import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Color
import android.os.Bundle
import android.os.Environment
import android.util.Log
import android.view.SurfaceHolder
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.hb.anative.NativeWindowSample.Companion.MEDIA_PARAM_VIDEO_DURATION
import com.hb.anative.NativeWindowSample.Companion.MEDIA_PARAM_VIDEO_HEIGHT
import com.hb.anative.NativeWindowSample.Companion.MEDIA_PARAM_VIDEO_WIDTH
import com.hb.anative.NativeWindowSample.Companion.MSG_DECODER_DONE
import com.hb.anative.NativeWindowSample.Companion.MSG_DECODER_INIT_ERROR
import com.hb.anative.NativeWindowSample.Companion.MSG_DECODER_READY
import com.hb.anative.NativeWindowSample.Companion.MSG_REQUEST_RENDER
import com.hb.anative.NativeWindowSample.Companion.VIDEO_RENDER_ANWINDOW


class MainActivity : AppCompatActivity() {
    private val TAG = "ANative"
    private val mVideoPath =
        Environment.getExternalStorageDirectory().absolutePath + "/byteflow/one_piece.mp4"
    private val path = "/storage/emulated/0/qiqiu.mp4"

    val n by lazy { NativeWindowSample() }
    val sv by lazy(LazyThreadSafetyMode.NONE) { findViewById<MySurfaceView>(R.id.sv) }
    var player: NativeWindowSample? = null
    val iv by lazy { findViewById<ImageView>(R.id.iv) }

    val options = BitmapFactory.Options().apply { inScaled = false }
    val bm by lazy { BitmapFactory.decodeResource(resources, R.mipmap.ic_launcher, options) }
    val bm1 by lazy { BitmapFactory.decodeResource(resources, R.mipmap.ic_launcher_round, options) }

    var switch = false
    var switchBm = false
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

//        ConstraintLayoutStates
        // Example of a call to a native method
        findViewById<TextView>(R.id.sample_text).text = n.stringFromJNI()

        storagePermission {
            if (it) Toast.makeText(this, "需要读取文件！", Toast.LENGTH_SHORT).show()
        }
        initEvent()

        Log.d(TAG, "hb onCreate: 是否打印日志${BuildConfig.HB_DEBUG}")
    }

//    /**
//     * A native method that is implemented by the 'native-lib' native library,
//     * which is packaged with this application.
//     */
//    external fun stringFromJNI(): String
//
//    companion object {
//        // Used to load the 'native-lib' library on application startup.
//        init {
//            System.loadLibrary("native-lib")
//        }
//    }

    fun drawBg(view: View) {
        n.drawColor(sv.holder.surface, if (switch) Color.GRAY else Color.RED)
        switch = !switch
    }

    fun drawBm(view: View) {
//        val options = BitmapFactory.Options()
//        options.inScaled = false
//        val bitmap = BitmapFactory.decodeResource(resources, R.mipmap.ic_launcher, options)
//        val bitmap1 = BitmapFactory.decodeResource(resources, R.mipmap.ic_launcher_round, options)

//        n.drawBitmap(sv.holder.surface, if (switchBm) bm else bm1)
        n.setBitmap(bm)
        switchBm = !switchBm
    }

    fun getBm(view: View) {
//        val bmArray = n.nativeBitmap(bm1)
////        val options = BitmapFactory.Options()
////        options.inSampleSize = 8
//        println(bmArray.contentToString())
//        val bmm = BitmapFactory.decodeByteArray(bmArray, 0, bmArray.size)
//        println("bmArray size:${bmArray.size} bmm is $bmm")
//        iv.setImageBitmap(bmm)

/*        var ps = IntArray(bm.width * bm.height)
        bm1.getPixels(ps, 0, bm.width, 0, 0, bm.width, bm.height)
        val bmArr = n.nativeBitmapArray(ps)

        println(bmArr.contentToString())
        val bmm = BitmapFactory.decodeByteArray(bmArr, 0, bmArr.size)
        println("bmArray size:${bmArr.size} bmm is $bmm")
        iv.setImageBitmap(bmm)*/

/*
        var ps = IntArray(bm.width * bm.height)
        bm1.getPixels(ps, 0, bm.width, 0, 0, bm.width, bm.height)
        val bmArr = n.nativeBitmapIntArray(ps)

        println(bmArr.contentToString())
        val bmm = Bitmap.createBitmap(ps, bm1.width, bm1.height, Bitmap.Config.ARGB_8888)
        println("bmArray size:${bmArr.size} bmm is $bmm")
        iv.setImageBitmap(bmm)*/

        val bmArr = n.nativeBitmap(bm1);
        println(bmArr.contentToString())
        val bmm = Bitmap.createBitmap(bmArr, bm1.width, bm1.height, Bitmap.Config.ARGB_8888)
        println("bmArray size:${bmArr.size} bmm is $bmm")
        iv.setImageBitmap(bmm)

    }

    fun test() {
        synchronized(this) {

        }
    }

    private fun initEvent() {
        val event = object : NativeWindowSample.EventCallback {
            override fun onPlayerEvent(msgType: Int, msgValue: Float) {
                Log.d(
                    "ANative",
                    "onPlayerEvent() called with: msgType = [$msgType], msgValue = [$msgValue]"
                )
                runOnUiThread {
                    when (msgType) {
                        MSG_DECODER_INIT_ERROR -> {
                        }
                        MSG_DECODER_READY -> onDecoderReady()
                        MSG_DECODER_DONE -> {
                        }
                        MSG_REQUEST_RENDER -> {
                        }
//                        MSG_DECODING_TIME -> if (!mIsTouch) mSeekBar.setProgress(msgValue.toInt())
                        else -> {
                        }
                    }
                }
            }
        }


        val callback = object : SurfaceHolder.Callback {
            override fun surfaceCreated(holder: SurfaceHolder) {
                Log.d(TAG, "surfaceCreated() called with: surfaceHolder = [$holder]")
                player = NativeWindowSample()
                          player?.addEventCallback(event)
      player?.init(mVideoPath, VIDEO_RENDER_ANWINDOW, holder.surface)
                player?.setBitmap(bm)
            }

            override fun surfaceChanged(
                holder: SurfaceHolder,
                format: Int,
                width: Int,
                height: Int
            ) {
                Log.d(
                    TAG,
                    "surfaceChanged() called with: surfaceHolder = [$holder], format = [$format], w = [$width], h = [$height]"
                )
                player?.play()
            }

            override fun surfaceDestroyed(holder: SurfaceHolder) {
                Log.d(
                    TAG,
                    "surfaceDestroyed() called with: surfaceHolder = [$holder]"
                )
                player?.unInit()
            }
        }

        sv.holder.addCallback(callback)
    }

    private fun onDecoderReady() {
        val videoWidth = player!!.getMediaParams(MEDIA_PARAM_VIDEO_WIDTH).toInt()
        val videoHeight = player!!.getMediaParams(MEDIA_PARAM_VIDEO_HEIGHT).toInt()
        if (videoHeight * videoWidth != 0) sv.setAspectRatio(videoWidth, videoHeight)
        val duration = player!!.getMediaParams(MEDIA_PARAM_VIDEO_DURATION).toInt()
/*        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            mSeekBar.setMin(0)
        }
        mSeekBar.setMax(duration)*/
    }

    override fun onResume() {
        super.onResume()
        player?.play()
    }

    override fun onPause() {
        super.onPause()
        player?.pause()
    }

    override fun onDestroy() {
        super.onDestroy()
        player = null
    }
}